#include "log.h"
#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include <QDir>
#include <QDebug>

Log::Log(QStandardItemModel *model, QObject *parent)
    : QObject(parent), m_model(model), m_filePath("app_log.txt")
{
    // 确保目录存在
    QFileInfo fileInfo(m_filePath);
    if(!fileInfo.dir().exists()){
        fileInfo.dir().mkpath("."); // 创建所有必要的父目录
    }

    // 设置表格标题
    m_model->setHorizontalHeaderLabels({"时间", "内容"});

    // 如果文件不存在则创建
    if(!fileInfo.exists()){
        QFile file(m_filePath);
        if(file.open(QIODevice::WriteOnly | QIODevice::Text)){
            QTextStream out(&file);
            out.setCodec("UTF-8");
            out << QString("日志文件创建于 %1\n").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
            file.close();
        }
    }

    // 读取已有日志
    readlog();
}

void Log::writefile(const QString &message)
{
    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString logEntry = QString("[%1] %2").arg(time, message);

    // 确保文件可写
    QFile file(m_filePath);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
        QTextStream out(&file);
        out.setCodec("UTF-8");
        out << logEntry << "\n";
        file.close();
    }
    else
    {
        qDebug() << "无法写入日志文件:" << file.errorString();
    }

    // 更新界面模型
    QList<QStandardItem*> row;
    row << new QStandardItem(time);
    row << new QStandardItem(message);
    m_model->insertRow(0, row);
}

void Log::readlog()
{
    QFile file(m_filePath);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text)){
        QTextStream in(&file);
        in.setCodec("UTF-8");

        while(!in.atEnd()){
            QString line = in.readLine();
            QStringList parts = line.split("] ");

            if(parts.count() == 2){
                QString time = parts[0].mid(1);
                QString content = parts[1];

                QList<QStandardItem*> row;
                row << new QStandardItem(time);
                row << new QStandardItem(content);
                m_model->insertRow(0, row);
            }
        }
        file.close();
    }
}
